package com.xmtlxx.web.controller.system;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.common.constant.Constants;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.domain.entity.SysMenu;
import com.xmtlxx.common.core.domain.entity.SysUser;
import com.xmtlxx.common.core.domain.model.LoginBody;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.RSAUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.redis.RedisUtils;
import com.xmtlxx.system.domain.vo.RouterVo;
import com.xmtlxx.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author xmtlxx
 */
@Validated
@Api(value = "登录验证控制器", tags = {"登录验证管理"})
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;
    private final ISysConfigService configService;
    private final SysPermissionService permissionService;

    @ApiOperation("获取加密公钥")
    @GetMapping("/publicKey")
    public R<Map<String, Object>> publicKey() {
        Map<String, Object> ajax = new HashMap<>();
        try {
            Map<String, Object> keyMap = RSAUtils.genKeyPair();
            String publicKey = RSAUtils.getPublicKey(keyMap);
            String privateKey = RSAUtils.getPrivateKey(keyMap);
            // 保存私钥信息
            String uuid = IdUtil.simpleUUID();
            String privateKeyKey = Constants.PRIVATE_KEY_KEY + uuid;

            RedisUtils.setCacheObject(privateKeyKey, privateKey, Constants.PRIVATE_KEY_EXPIRATION, TimeUnit.MINUTES);
            ajax.put("uuid", uuid);
            ajax.put("publicKey", publicKey);
            return R.ok(ajax);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail("错误：访问密钥加载失败，请重试！");
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        String privateKeyKey = Constants.PRIVATE_KEY_KEY + StringUtils.defaultString(loginBody.getKeyUuid(), "");
        String privateKey = RedisUtils.getCacheObject(privateKeyKey);
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        if(captchaOnOff){
            //判断账号是否需要验证码
            String users = configService.selectConfigByKey(Constants.SYS_PHONE_KEY);
            if(!users.contains(loginBody.getUsername())){
                String redisCode = RedisUtils.getCacheObject(loginBody.getUsername());
                if(redisCode != null){
                    if(!redisCode.equals(loginBody.getCode())){
                        return R.fail("手机验证码错误，请重新获取,重新登陆！");
                    }
                }else{
                    return R.fail("手机验证码超时，请重新获取,重新登陆！");
                }
            }
        }
        String password = loginBody.getPassword();
        if (privateKey == null) {
            return R.fail("鉴权失败，请刷新页面,重新登陆！");
        }
        try {
            password = RSAUtils.decryptDataOnJava(password, privateKey);
        } catch (Exception e) {
            return R.fail("鉴权失败，请刷新页面,重新登陆！");
        }
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), password, loginBody.getCode(),
            loginBody.getUuid(),loginBody.getDeviceId());
        ajax.put(Constants.TOKEN, token);
        RedisUtils.deleteObject(privateKeyKey);
        return R.ok(ajax);
    }

    @ApiOperation("登出方法")
    @PostMapping("/logout")
    public R<Void> logout() {
        try {
            StpUtil.logout();
            loginService.logout(LoginHelper.getUsername());
        } catch (NotLoginException e) {
        }
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        SysUser user = userService.selectUserById(LoginHelper.getUserId());
        user.setDeviceId(LoginHelper.getDeviceId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return R.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
